<?php
/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 * 
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @category    EveBit_Library
 * @package     Application
 * @author      Cheng Wei <berlios.o@gmail.com>
 * @version     $$Id: Bootstrap.php 1434 2011-06-27 09:51:09Z chen.hao $$
 * @copyright   Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */

/**
 * Main Bootstrap
 * 
 * @package     Application
 * @author      Cheng Wei <berlios.o@gmail.com>
 * @version     $$Id: Bootstrap.php 1434 2011-06-27 09:51:09Z chen.hao $$
 */
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
	
	/**
	 * Init default event for zend
	 */
	protected function _initEvent() {
		if (!Zend_Registry::isRegistered('Evebit_Event_Observer')) {
			
			$config = $this->getOption('events');
			if (!is_array($config)) {
				$config = array();
			}
			
			Evebit_Event_Observer::getInstance()->init($config);
		}
	}
	
	/**
	 * Init Acl for user by Zend_Acl
	 */
	protected function _initAcl() {
		if (!Zend_Registry::isRegistered('Acl')) {
			$cacheKeyForAcl = "global_acl";
			$this->_initCache();
			$this->_initConfig();
			$cache = $this->getApplication()->getCache();
			if (!$cache->test($cacheKeyForAcl)) {
				try {
					$resource = new Default_Model_Entity_Resource();
					$roleResource = new Default_Model_Entity_RoleResource();
					$resources = $resource->getCollection()->getItems();
					$roleResources = $roleResource->getCollection()->getItems();
					
					$acl = new Zend_Acl();
					
					foreach ($resources as $resource) {
						$resourceName = $resource->getScope()."-".$resource->getModule()."-".$resource->getController();

						if ($resource->getAction() != "index") {
							$resourceName .= "-" . $resource->getAction();
						}
						if ($resource->getParams() != "") {
							$resourceName .= "-" . $resource->getParams();
						}
						if (!$acl->has($resourceName)) {
							$acl->add(new Zend_Acl_Resource($resourceName));
						}
					    foreach ($roleResources as $roleResource) {
							
							if (!$acl->hasRole($roleResource->getRoleName())) {
								$acl->addRole(
									new Zend_Acl_Role($roleResource->getRoleName()));
							}
							if ($resourceName == $roleResource->getAllowResouce()) {
								$acl->allow($roleResource->getRoleName(), 
									$roleResource->getAllowResouce());
							}
						}
					}
					
					/*foreach ($resources as $resource) {
						$resourceName = $resource->getScope()."-".$resource->getController();
						if ($resource->getAction() != "index") {
							$resourceName .= "-" . $resource->getAction();
						}
						if ($resource->getParams() != "") {
							$resourceName .= "-" . $resource->getParams();
						}
						foreach ($roleResources as $roleResource) {
							
							if (!$acl->hasRole($roleResource->getRoleName())) {
								$acl->addRole(
									new Zend_Acl_Role($roleResource->getRoleName()));
							}
							if ($resourceName == $roleResource->getAllowResouce()) {
								$acl->allow($roleResource->getRoleName(), 
									$roleResource->getAllowResouce());
							}
						}
					}*/
					$cache->save($acl, $cacheKeyForAcl, array('GLOBAL_CACHE'));
					Zend_Registry::set('Acl', $acl);
				} catch (Exception $e) {
					print_r($e->getMessage());
					print_r($e->getLine());
					exit();
				}
			
			} else {
				$acl = $cache->load($cacheKeyForAcl);
				Zend_Registry::set('Acl', $acl);
			}
		}
	}
	/**
	 * Init default cache for zend
	 */
	protected function _initCache() {
		/* @var $cacheManager Zend_Application_Resource_Cachemanager */
		if (!Zend_Registry::isRegistered('Cache')) {
			$cacheManager = $this->bootstrap('cacheManager')->getResource('cacheManager');
			$cache = $cacheManager->getCache('default');
			
			Zend_Locale::setCache($cache);
			Zend_Translate::setCache($cache);
			Zend_Registry::set('Cache', $cache);
			Zend_Db_Table::setDefaultMetadataCache($cache);
		}
	}
	
	/**
	 * Init default routes
	 */
	protected function _initRoutes() {
		/**
		 * Here can be placed the default global routes 
		 */
		$frontController = $this->getPluginResource('frontController');
		$file = $this->getApplication()->getScope();
		$config = new Zend_Config_Ini(AP . DS . 'configs' . DS . $file . '.ini', 'production');
		if ($config->routes) {
			$router = new Zend_Controller_Router_Rewrite();
			$router->addConfig($config, 'routes');
			$frontController->getRouter()->addRoutes($router->getRoutes());
		}
	}
	
	/**
	 * Init default request
	 */
	protected function _initRequest() {
		/*$this->bootstrap('modules');
		
		$url_rewrite = new Information_Model_Entity_Url_Rewrite();
		$url_rewrite->getAll();
		$datas = $url_rewrite->getData();
		
		$frontController = $this->bootstrap('FrontController')->getResource('FrontController');
		
		if ($frontController->getRequest() === null) {
			$request = new Zend_Controller_Request_Http();
			$frontController->setRequest($request);
		} else {
			$request = $frontController->getRequest();
		}
		
		foreach ($datas as $item) {
			if ($item['target_url'] == substr($request->getPathInfo(), 1)) {
				$request->setPathInfo('/' . $item['original_url']);
				break;
			}
		}*/
	}
	
	/**
	 * Init cache the exception of clientLogin
	 */
	protected function _initClientLogin() {
		if (!Zend_Registry::isRegistered('clientLoginCatch')) {
			$clientLogin = $this->getApplication()->getOption('clientLogin');
			$catch = $clientLogin['exception']['network']['catch'];
			Zend_Registry::set('clientLoginCatch', $catch);
		}
	}
	
	/**
	 * load config from database, and save to registry
	 */
	protected function _initConfig() {
		if (!Zend_Registry::isRegistered("configs")) {
			$this->bootstrap('modules');
			$this->bootstrap('db');
			
			// load configuration from DB
			$cacheKeyForConfig = "global_configuration";
			$cache = $this->getApplication()->getCache();
			if (!$cache->test($cacheKeyForConfig)) {
				$config = new Default_Model_Entity_Config();
				$configs = $config->loadConfigurations();
				$cache->save($configs, $cacheKeyForConfig, array('GLOBAL_CACHE'));
			} else {
				$configs = $cache->load($cacheKeyForConfig);
			}
			Zend_Registry::set("configs", $configs);
			$this->getApplication()->mergeConfig($configs);
			// set timezone
			$timezone = $this->getApplication()->getConfig('default_timezone');
			if ($timezone) {
				date_default_timezone_set($timezone);
			}
		}
	
	}
}

/**
 * Main Bootstrap
 * 
 * @package     App_Sample
 * @author      Cheng Wei <berlios.o@gmail.com>
 * @version     $$Id: Bootstrap.php 1434 2011-06-27 09:51:09Z chen.hao $$
 */
class Bootstrap_Cron extends Bootstrap {
	
	/**
	 * Run the application
	 *
	 * Checks to see that we have a default controller directory. If not, an
	 * exception is thrown.
	 *
	 * If so, it registers the bootstrap with the 'bootstrap' parameter of
	 * the front controller, and dispatches the front controller.
	 *
	 * @return mixed
	 * @throws Zend_Application_Bootstrap_Exception
	 */
	public function run() {
		/* @var $front Zend_Controller_Front */
		$front = $this->getResource('FrontController');
		
		$front->setParam('bootstrap', $this);
		
		$front->setParam('noViewRenderer', true);
		Zend_Layout::getMvcInstance()->disableLayout();
		
		$action = 'index';
		$controller = 'index';
		$module = 'cron';
		$params = array();
		
		if (!isset($GLOBALS['argv'])) {
			$argv = array_keys($_REQUEST);
		} else {
			$argv = $GLOBALS['argv'];
		}
		array_shift($argv);
		
		define('CRON_ARGV', implode(" ", $argv));
		
		if ($argv) {
			$line = array_shift($argv);
			$tokens = explode('/', trim($line, '/'));
			if (count($tokens) >= 3) {
				$action = $tokens[2];
				$controller = $tokens[1];
				$module = $tokens[0];
			} elseif (count($tokens) == 2) {
				$action = $tokens[1];
				$controller = $tokens[0];
			} elseif (count($tokens) == 1) {
				$action = $tokens[0];
			}
			while ($argv) {
				$line = array_shift($argv);
				if (preg_match("/^--([a-z0-9_-]+)=(.*)$/", $line, $match)) {
					$params[$match[1]] = trim($match[2]);
				}
			}
		}
		
		$front->setRequest(
			new Zend_Controller_Request_Simple($action, $controller, $module, $params));
		$front->setResponse(new Zend_Controller_Response_Cli());
		$front->setRouter(new Evebit_Controller_Router_Cli());
		
		$response = $front->dispatch();
		if ($front->returnResponse()) {
			return $response;
		}
	}

}

